package com.group.eams.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.group.eams.service.impl.UserServiceImpl;
import com.group.eams.threadlocal.UserThreadLocal;
import com.group.eams.threadlocal.UserThreadLocalDto;
import com.group.result.Result;
import com.group.result.ResultEnum;
import com.group.utils.JsonUtils;
import com.group.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * com.group.eams.interceptor
 * user: 恩哲欣
 * Date: 2024/10/29 14:02
 * Motto: Where there is a will, there is a way!
 * Description:
 * Version: V1.0
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader("token");

        if(StrUtil.isEmpty(token)){
            Result result = Result.buildFail(ResultEnum.TOKEN_NOT_EMPTY);
            ResponseUtils.responseToJson(response, JsonUtils.objectToJson(result));
            return false;
        }


        //2.校验jwt令牌的合法性
        if(!JWTUtil.verify(token, UserServiceImpl.secret.getBytes())){
            Result result = Result.buildFail(ResultEnum.TOKEN_ERROR);
            ResponseUtils.responseToJson(response, JsonUtils.objectToJson(result));
            return false;
        }

        //合法，解析 载荷
        JWT jwt = JWTUtil.parseToken(token);

        //3.判断是否失效
        Long expireTime = (Long) jwt.getPayload("expireTime");
        if(new Date().getTime()>expireTime){
            Result result = Result.buildFail(ResultEnum.TOKEN_EXPIRED);
            ResponseUtils.responseToJson(response, JsonUtils.objectToJson(result));
            return false;
        }

        //4.获取其它载荷绑定到当前线程
        UserThreadLocalDto userThreadLocalDto=new UserThreadLocalDto();
        userThreadLocalDto.setId(((Integer) jwt.getPayload("id")).longValue());
        userThreadLocalDto.setName((String) jwt.getPayload("name"));
        userThreadLocalDto.setAccount((String) jwt.getPayload("account"));
        userThreadLocalDto.setSex((Integer) jwt.getPayload("sex"));
        userThreadLocalDto.setPhone((String) jwt.getPayload("phone"));
        userThreadLocalDto.setImage((String) jwt.getPayload("image"));
        userThreadLocalDto.setEmail((String) jwt.getPayload("email"));

        String  permissionPermsList = (String) jwt.getPayload("permissionPermsList");
        if(!StrUtil.isEmpty(permissionPermsList)){
            log.debug("解析到用户携带的权限信息:{},绑定到当前线程",permissionPermsList);
            List<String> list = JsonUtils.jsonToList(permissionPermsList, String.class);
            userThreadLocalDto.setPermissionPermsList(list);
        }

        //绑定用户信息到当前线程
        UserThreadLocal.set(userThreadLocalDto);

        //5.放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //移除当前线程绑定的用户信息
        UserThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
